<template>
  <div class="pt-16 flex justify-center bg-background-900 min-h-screen">
    <!-- 加载状态 -->
    <LoadingSpinner v-if="isLoading" />

    <!-- 主要内容 -->
    <div v-else-if="movie" class="max-w-6xl w-full flex flex-col gap-6 p-4">
      <!-- 视频播放器 -->
      <MoviePlayer :movie="movie" :is-loading="isLoading" />

      <!-- 基本信息 -->
      <MovieBasicInfo :movie="movie" />

      <!-- 内容区域 -->
      <div class="flex gap-6">
        <!-- 左侧内容区域 -->
        <div class="flex-1 flex flex-col gap-6">
          <!-- 评论区 -->
          <CommentSection :movie-id="movie.id" />
        </div>

        <!-- 右侧推荐栏 -->
        <div class="hidden xl:block w-80 flex-shrink-0">
          <RecommendSidebar :movies="relatedMovies" :is-loading="isLoading" />
        </div>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="!isLoading" class="flex items-center justify-center w-full h-64">
      <div class="text-center">
        <div class="text-text-secondary text-lg mb-2">电影不存在或已被删除</div>
        <UiButton
          @click="$router.push('/')"
          variant="primary"
        >
          返回首页
        </UiButton>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, ref, watch } from 'vue'
  import { useRoute } from 'vue-router'
  import { useMovieDetail } from '../composables/movies'
  import MoviePlayer from '../components/movie/MoviePlayer.vue'
  import MovieBasicInfo from '../components/movie/MovieBasicInfo.vue'
  import CommentSection from '../components/movie/CommentSection.vue'
  import RecommendSidebar from '../components/movie/RecommendSidebar.vue'
  import { LoadingSpinner, UiButton } from '../components/ui'

  const route = useRoute()
  const { isLoading, movie, relatedMovies, loadMovieDetail, loadRelatedMovies } = useMovieDetail()

  // 加载电影数据的函数
  const loadMovieData = async (movieId: number) => {
    console.log('Loading movie data for ID:', movieId)
    try {
      await Promise.all([loadMovieDetail(movieId), loadRelatedMovies(movieId)])
      
      // 确保页面滚动到顶部 - 针对MainLayout中的滚动容器
      const mainContent = document.querySelector('main')
      if (mainContent) {
        mainContent.scrollTop = 0
      } else {
        window.scrollTo(0, 0)
      }
    } catch (error) {
      console.error('Failed to load movie details:', error)
    }
  }

  // 监听路由参数变化
  watch(
    () => route.params.id,
    (newId, oldId) => {
      console.log('Route ID changed from', oldId, 'to', newId)
      const movieId = parseInt(newId as string)
      if (!isNaN(movieId)) {
        loadMovieData(movieId)
      }
    },
    { immediate: true } // 立即执行一次
  )

  onMounted(async () => {
    const movieId = parseInt(route.params.id as string)
    if (!isNaN(movieId)) {
      await loadMovieData(movieId)
    }
  })
</script>
